package com.yh.blog.controller.admin;

import com.yh.blog.domain.Types;
import com.yh.blog.service.TypesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 分类管理控制层
 */
@Controller
@RequestMapping("/admin")
public class TypesController {
    @Autowired
    private TypesService typesService;

//    分类列表
    @GetMapping("/types")
    public String index(Model model, @RequestParam(value = "page",defaultValue = "1") Integer page){
        model.addAttribute("pager",this.typesService.list(page));
        return "admin/types/types";

    }

//  跳转到新增分类页面
    @GetMapping("/types/input")
    public String input(){
        return "admin/types/types-append";
    }
//    新增分类
    @PostMapping("/types")
    public String append(Types type, RedirectAttributes attributes){
        if(this.typesService.append(type)){
            attributes.addFlashAttribute("messages","新增成功");
        }else {
            attributes.addFlashAttribute("messages","新增失败");
        }
        return "redirect:/admin/types";
    }

//    跳转到编辑分类页面
    @GetMapping("/types/{typesId}/input")
    public String editInput(@PathVariable Integer typesId, Model model) {
        model.addAttribute("type",this.typesService.detail(typesId));
        return "admin/types/types-modify";
    }
//    编辑分类
    @PostMapping("/types/modify")
    public String editPost(Integer typesId, String typesName,RedirectAttributes attributes) {
        if(this.typesService.modifyTypeName(typesId,typesName)){
            attributes.addFlashAttribute("messages","修改成功");
        }else {
            attributes.addFlashAttribute("messages","修改失败");
        }
        return "redirect:/admin/types";
    }

//    @ResponseBody
//    @RequestMapping("/isExistsByName")
//    public boolean isExistsByName(String typesName) {
//        return this.typesService.typesNameIsExists(typesName);
//    }

//  删除分类
    @RequestMapping("/types/delete")
    public String delete(Integer typesId, RedirectAttributes attributes){
        this.typesService.remove(typesId);
        attributes.addFlashAttribute("messages","删除成功");
        return "redirect:/admin/types";
    }
}
